<?php

// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var    数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, true);
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

/**
 * 求两个已知经纬度之间的距离,单位为米
 *
 * @param lng1 $ ,lng2 经度
 * @param lat1 $ ,lat2 纬度
 * @return float 距离，单位米 保留两位小数
 * @author www.Alixixi.com
 */
function getdistance($lng1, $lat1, $lng2, $lat2) {
    // 将角度转为狐度
    $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
    $s = sprintf("%.2f", $s);
    return $s;
}

/**
 * 求两个已知经纬度之间的距离,单位为千米
 *
 * @param lng1 $ ,lng2 经度
 * @param lat1 $ ,lat2 纬度
 * @return float 距离，单位米 保留两位小数
 * @author www.Alixixi.com
 */
function getdistancekm($lng1, $lat1, $lng2, $lat2) {
    // 将角度转为狐度
    $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
    $s = sprintf("%.2f", $s);
    return $s;
}

//指定数组以$keys键值排序
function array_sort($array,$keys,$type='asc'){
//$array为要排序的数组,$keys为要用来排序的键名,$type默认为升序排序
    $keysvalue = $new_array = array();
    foreach ($array as $k=>$v){
        $keysvalue[$k] = $v[$keys];
    }
    if($type == 'asc'){
        asort($keysvalue);
    }else{
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k=>$v){
        $new_array[$k] = $array[$k];
    }
    return $new_array;
}

//根据积分更新会员等级

function updateLevel($score,$uid){
    try{

        $level = "";
        $res = model('Config')->where("name='userlevel'")->field("value")->find();
        if($res){
            $restmp = $res->toarray()["value"];
            $serviceList = json_decode($restmp,true);

            $keys = array_keys($serviceList);
            $len = count($keys);
            $vals = array_values($serviceList);


            for($i=0;$i<$len-1;$i++){
                $varr = explode("|",$vals[$i]);

                if($score < $varr[1]){
                    $level = $keys[$i];
                    break;
                }else{
                    $level = $keys[$len-1];
                }
            }



            if(db("user")->where(["id"=>$uid])->update(["level"=>$level,"score"=>$score,"updatetime"=>time()])){
                return true;
            }else{
                return false;
            }

        }

    }catch (\think\exception\PDOException $e) {
        $this->error($e->getMessage());
    } catch (\think\Exception $e) {
        $this->error($e->getMessage());
    }





}

//截取字符串长度

function subText($text, $length)
{
    if (mb_strlen($text, 'utf8') > $length) {
        return mb_substr($text, 0, $length, 'utf8') . '';
    } else {
        return $text;
    }
}

function subText2($text, $length)
{
    if (mb_strlen($text, 'utf8') > $length) {
        return mb_substr($text, 0, $length, 'utf8') . '';
    } else {
        return $text;
    }
}

function subText3($text, $length)
{
    if (mb_strlen($text, 'utf8') > $length) {
        return mb_substr($text, 0, $length, 'utf8') . '...';
    } else {
        return $text;
    }
}
function subText4($text, $length)
{
    if (mb_strlen($text, 'utf8') > $length) {
        return mb_substr($text, 24, $length, 'utf8') . '';
    } else {
        return $text;
    }
}

//发送短信 房费到期提醒 发给用户
function sendmsg($mobile){
    $template = "SMS_209820774";
    $sign="云渚分时住";
    $alisms = new \addons\alisms\library\Alisms();

    $ret = $alisms->mobile($mobile)
        ->template($template)
        ->sign($sign)
        ->param([])
        ->send();

    if ($ret) {
        return 1;
    } else {
        return $alisms->getError();
    }

}

//发送短信 房费到期提醒酒店 发给酒店 app端手动触发
function sendHotel($mobile){
    $template = "SMS_215060022";
    $sign="云渚分时住";
    $alisms = new \addons\alisms\library\Alisms();

    $ret = $alisms->mobile($mobile)
        ->template($template)
        ->sign($sign)
        ->param(["number"=>$mobile])
        ->send();

    if ($ret) {
        return 1;
    } else {
        return $alisms->getError();
    }

}

//发送短信 房费到期提醒酒店 发给酒店
function sendHmsg($mobile,$name){
    $template = "SMS_209827096";
    $sign="云渚分时住";
    $alisms = new \addons\alisms\library\Alisms();

    $ret = $alisms->mobile($mobile)
        ->template($template)
        ->sign($sign)
        ->param(["username"=>$name,"number"=>$mobile])
        ->send();

    if ($ret) {
        return 1;
    } else {
        return $alisms->getError();
    }

}

//发送短信 预定成功通知用户 发给用户
function sendUmsg($mobile,$uphone){
    $template = "SMS_209830790";
    $sign="云渚分时住";
    $alisms = new \addons\alisms\library\Alisms();

    $ret = $alisms->mobile($mobile)
        ->template($template)
        ->sign($sign)
        ->param(["number"=>$uphone])
        ->send();

    if ($ret) {
        return 1;
    } else {
        return $alisms->getError();
    }

}

//发送短信 用户退房短发 发送给用户
function sendCmsg($mobile,$uphone){
    $template = "SMS_209830790";
    $sign="云渚分时住";
    $alisms = new \addons\alisms\library\Alisms();

    $ret = $alisms->mobile($mobile)
        ->template($template)
        ->sign($sign)
        ->param(["number"=>$uphone])
        ->send();

    print_r($alisms->getError());die;


    if ($ret) {
        return 1;
    } else {
        return $alisms->getError();
    }

}

//发送短信 房间预定成功酒店 发给酒店
function sendHOmsg($mobile,$name){
    $template = "SMS_209820768";
    $sign="云渚分时住";
    $alisms = new \addons\alisms\library\Alisms();

    $ret = $alisms->mobile($mobile)
        ->template($template)
        ->sign($sign)
        ->param(["username"=>$name,"number"=>$mobile])
        ->send();

    if ($ret) {
        return 1;
    } else {
        return $alisms->getError();
    }

}

//发送短信 取消房源 发给用户
function sendmsgUCancel($mobile,$money,$hphone){
    $template = "SMS_210060099";
    $sign="云渚分时住";
    $alisms = new \addons\alisms\library\Alisms();

    $ret = $alisms->mobile($mobile)
        ->template($template)
        ->sign($sign)
        ->param(["money"=>$money,"number"=>$hphone])
        ->send();

    if ($ret) {
        return 1;
    } else {
        return $alisms->getError();
    }

}


//发送短信 取消房源 发给酒店
function sendmsgHCancel($mobile,$username,$number){
    $template = "SMS_210055223";
    $sign="云渚分时住";
    $alisms = new \addons\alisms\library\Alisms();

    $ret = $alisms->mobile($mobile)
        ->template($template)
        ->sign($sign)
        ->param(["username"=>$username,"number"=>$number])
        ->send();

    if ($ret) {
        return 1;
    } else {
        return $alisms->getError();
    }

}



//动态计算几天是周几 返回不同的价格 周五 周六 返回周末价格

function getToday($date){
    $w=date('w',$date);
    $week=array(
        "0"=>"周日",
        "1"=>"周一",
        "2"=>"周二",
        "3"=>"周三",
        "4"=>"周四",
        "5"=>"周五",
        "6"=>"周六"
    );

    return $week[$w];

}



function arr2str ($arr)
{
    foreach ($arr as $v)
    {
        $v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串
        $temp[] = $v;
    }
    $t="";
    foreach($temp as $v){
        $t.=$v.",";
    }
    $t=substr($t,0,-1);
    return $t;
}



//海报相关方法


/**
 * 生成宣传海报 如果已知用户信息 也可以 一次性生成完整海报
 * @param array  参数,包括图片和文字
 * @param string  $filename 生成海报文件名,不传此参数则不生成文件,直接输出图片
 * @return [type] [description]
 */
function createPoster($config=array(),$filename=""){
    //如果要看报什么错，可以先注释调这个header
    if(empty($filename)) header("content-type: image/png");
    $imageDefault = array(
        'left'=>0,
        'top'=>0,
        'right'=>0,
        'bottom'=>0,
        'width'=>100,
        'height'=>100,
        'opacity'=>100
    );
    $textDefault = array(
        'text'=>'',
        'left'=>0,
        'top'=>0,
        'fontSize'=>32,       //字号
        'fontColor'=>'255,255,255', //字体颜色
        'angle'=>0,
    );
    $background = $config['background'];//海报最底层得背景
    //背景方法
    $backgroundInfo = getimagesize($background);
    $backgroundFun = 'imagecreatefrom'.image_type_to_extension($backgroundInfo[2], false);
    $background = $backgroundFun($background);
    $backgroundWidth = imagesx($background);  //背景宽度
    $backgroundHeight = imagesy($background);  //背景高度
    $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight);
    $color = imagecolorallocate($imageRes, 0, 0, 0);
    imagefill($imageRes, 0, 0, $color);
    // imageColorTransparent($imageRes, $color);  //颜色透明
    imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));
    //处理了图片
    if(!empty($config['image'])){
        foreach ($config['image'] as $key => $val) {
            $val = array_merge($imageDefault,$val);
            $info = getimagesize($val['url']);
            $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
            if($val['stream']){   //如果传的是字符串图像流
                $info = getimagesizefromstring($val['url']);
                $function = 'imagecreatefromstring';
            }
            $res = $function($val['url']);
            $resWidth = $info[0];
            $resHeight = $info[1];
            //建立画板 ，缩放图片至指定尺寸
            $canvas=imagecreatetruecolor($val['width'], $val['height']);
            imagefill($canvas, 0, 0, $color);
            //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
            imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight);
            $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
            $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
            //放置图像
            imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左，上，右，下，宽度，高度，透明度
        }
    }
    //处理文字
    if(!empty($config['text'])){
        foreach ($config['text'] as $key => $val) {
            $val = array_merge($textDefault,$val);
            list($R,$G,$B) = explode(',', $val['fontColor']);
            $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
            $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
            $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
            imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
        }
    }
    //生成图片
    if(!empty($filename)){
        $res = imagejpeg ($imageRes,$filename,90); //保存到本地
        imagedestroy($imageRes);
        if(!$res) return false;
        return $filename;
    }else{
        imagejpeg ($imageRes);     //在浏览器上显示
        imagedestroy($imageRes);
    }
}

/**
 * 处理成圆图片,如果图片不是正方形就取最小边的圆半径,从左边开始剪切成圆形
 * @param string $imgpath [description] 支持本地图片和网络图片
 * @return [type] [description]
 */
function yuan_img($imgpath = 'images/avatar.jpg') {


    $src_img = imagecreatefromstring(file_get_contents($imgpath));

   /* $ext = pathinfo($imgpath);
    $src_img = null;
    switch ($ext['extension']) {
        case 'jpg':
            $src_img = imagecreatefromjpeg($imgpath);
            break;
        case 'png':
            $src_img = imagecreatefrompng($imgpath);
            break;
    }*/
    $wh = getimagesize($imgpath);
    $w = $wh[0];
    $h = $wh[1];
    $w = min($w, $h);
    $h = $w;
    $img = imagecreatetruecolor($w, $h);
    //这一句一定要有
    imagesavealpha($img, true);
    //拾取一个完全透明的颜色,最后一个参数127为全透明 254,189,1
    $bg = imagecolorallocatealpha($img, 254, 189, 1, 0);
    //$bg = imagecolorallocatealpha($img, 255, 255, 255, 0);
    imagefill($img, 0, 0, $bg);
    $r = $w / 2; //圆半径
    $y_x = $r; //圆心X坐标
    $y_y = $r; //圆心Y坐标
    for ($x = 0; $x < $w; $x++) {
        for ($y = 0; $y < $h; $y++) {
            $rgbColor = imagecolorat($src_img, $x, $y);
            if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                imagesetpixel($img, $x, $y, $rgbColor);
            }
        }
    }
    return $img;
}

/**
 * @param  string  $imgpath 源图片路径
 * @param  integer $radius  圆角半径长度默认为15,处理成圆型
 * @return [type]           [description]
 */
function radius_img($imgpath = './t.png', $radius = 15) {
    $ext     = pathinfo($imgpath);

    //兼容在图片是png 但实际图片不是png  根据后缀判断不符的时候
    $src_img = imagecreatefromstring(file_get_contents($imgpath));


   /* $src_img = null;
    switch ($ext['extension']) {
        case 'jpg':
            $src_img = imagecreatefromjpeg($imgpath);
            break;
        case 'png':
            $src_img = imagecreatefrompng($imgpath);
            break;
    }*/


    $wh = getimagesize($imgpath);
    $w  = $wh[0];
    $h  = $wh[1];
    // $radius = $radius == 0 ? (min($w, $h) / 2) : $radius;
    $img = imagecreatetruecolor($w, $h);
    //这一句一定要有
    imagesavealpha($img, true);
    //拾取一个完全透明的颜色,最后一个参数127为全透明
    // $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
    $bg = imagecolorallocatealpha($img, 254, 189, 1, 0);
    imagefill($img, 0, 0, $bg);
    $r = $radius; //圆 角半径
    for ($x = 0; $x < $w; $x++) {
        for ($y = 0; $y < $h; $y++) {
            $rgbColor = imagecolorat($src_img, $x, $y);
            if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
                //不在四角的范围内,直接画
                imagesetpixel($img, $x, $y, $rgbColor);
            } else {
                //在四角的范围内选择画
                //上左
                $y_x = $r; //圆心X坐标
                $y_y = $r; //圆心Y坐标
                if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
                //上右
                $y_x = $w - $r; //圆心X坐标
                $y_y = $r; //圆心Y坐标
                if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
                //下左
                $y_x = $r; //圆心X坐标
                $y_y = $h - $r; //圆心Y坐标
                if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
                //下右
                $y_x = $w - $r; //圆心X坐标
                $y_y = $h - $r; //圆心Y坐标
                if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
    }
    return $img;
}

/**
 * @param  string  $source 源图片路径 绘制多边形
 * @param  string  $filename 生成图片名称
 * @param  string  $fonttff 字体
 * @param  string  $text1 显示内容1
 * @param  string  $text2 显示内容2
 * @return [type]           [description]
 */
function generateImg($source,$filename = "testdbx.png",$fonttff,$price,$preprice) {
    $font = $fonttff;
    $main = imagecreatefromjpeg( $source );
    $width = imagesx ( $main );
    $height = imagesy ( $main );
    $target = imagecreatetruecolor ( $width, $height );
    $white = imagecolorallocate ( $target, 255, 190, 4 );
    imagefill ( $target, 0, 0, $white );
    imagecopyresampled ( $target, $main, 0, 0, 0, 0, $width, $height, $width, $height );
    //绘制多边形
    $dbxColor = imagecolorallocate ( $target, 255, 190, 4 );//字的RGB颜色
    $points = array(
        570, 770,
        703, 770,
        703, 940,
        45, 940,
        45, 860,
        520, 860,
        300, 860,
    );
    imagefilledpolygon($target,$points,6,$dbxColor);
    //绘制文字
    $fontSize = 28;//像素字体
    $fontColor = imagecolorallocate ( $target, 255, 0, 0 );//字的RGB颜色
    $fontBox = imagettfbbox($fontSize, 0, $font, "优惠价");
    imagettftext ( $target, $fontSize, 0, ceil(($width - $fontBox[2]) / 2 + 250), 830, $fontColor, $font, "优惠价" );
    //绘制文字 原价
    $fontSize = 24;//像素字体
    $fontColor = imagecolorallocate ( $target, 0, 0, 0 );//字的RGB颜色
    $fontBox = imagettfbbox($fontSize, 0, $font, $preprice);
    imagettftext ( $target, $fontSize, 0, ceil(($width - $fontBox[2]) / 2 - 225), 910, $fontColor, $font, $preprice );
    //绘制文字 现价
    $fontSize = 32;//像素字体
    $fontColor = imagecolorallocate ( $target, 0, 0, 0 );//字的RGB颜色
    $fontBox = imagettfbbox($fontSize, 0, $font, $price);
    imagettftext ( $target, $fontSize, 0, ceil(($width - $fontBox[2]) / 2 + 265), 910, $fontColor, $font, $price );

    // @mkdir ( './' . $date );
    imagejpeg ( $target, $filename, 95 );
    imagedestroy ( $main );
    imagedestroy ( $target );
    return $filename;
}

//php计算两个时间相差的天数、小时数、分钟数、秒数
function getDatediffeall($stime,$etime){
    $startdate="2021-7-19 12:00:00";

    $enddate="2021-7-19 16:10:00";

    $date=floor((strtotime($enddate)-strtotime($startdate))/86400);
    echo "相差天数：".$date."天<br/><br/>";

    $hour=floor((strtotime($enddate)-strtotime($startdate))%86400/3600);
    echo "相差小时数：".$hour."小时<br/><br/>";

    $minute=floor((strtotime($enddate)-strtotime($startdate))%86400/60);
    echo "相差分钟数：".$minute."分钟<br/><br/>";

    $second=floor((strtotime($enddate)-strtotime($startdate))%86400%60);
    echo "相差秒数：".$second."秒";
}

//php计算两个时间相差的天数
function getDatediffeday($stime,$etime){
    $date=floor((strtotime($etime)-strtotime($stime))/86400);
    return $date;
}

//php计算两个时间相差的天数
function getDatediffedaytemp($stime,$etime){
    $date=floor(($etime-$stime)/86400);
    return $date;
}

//php计算两个时间相差的小时数、分钟数、秒数
function getDatediffehour($stime,$etime){
    $hour=floor((strtotime($etime)-strtotime($stime))%86400/3600);
    return $hour;
}

//php计算两个时间相差的小时数、分钟数、秒数
function getDatediffehourtemp($stime,$etime){
    $hour=floor(($etime-$stime)%86400/3600);
    return $hour;
}

//php计算两个时间相差的分钟数
function getDatediffemin($stime,$etime){
    $minute=floor((strtotime($etime)-strtotime($stime))%86400/60);
    return $minute;
}

//php计算两个时间相差的分钟数
function getDatediffemintemp($stime,$etime){
    $minute=floor(($etime-$stime)%86400/60);
    return $minute;
}

//PHP获取某个月第一天/最后一天代码
function getthemonth($date)
{
    $firstday = date('Y-m-01', strtotime($date));
    $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
    return array($firstday, $lastday);
}


//替换富文本图片为绝对路径
function pregReplaceImg2($content,$prefix)
{
    $contentAlter = preg_replace_callback('/(<[img|IMG].*?src=[\'\"])([\s\S]*?)([\'\"])[\s\S]*?/i', function($match)use($prefix){
        if(strstr($match[2], 'http://') == false && strstr($match[1], 'https://') == false)
            return $match[1].$prefix.$match[2].$match[3];
        else
            return $match[1].$match[2].$match[3];
    } , $content);
    return $contentAlter;
}

/**
 * 二维数组按照指定字段进行排序
 * @params array $array 需要排序的数组
 * @params string $field 排序的字段
 * @params string $sort 排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
 */
function arraySequence($array, $field, $sort = 'SORT_DESC') {
    $arrSort = array();
    foreach ($array as $uniqid => $row) {
        foreach ($row as $key => $value) {
            $arrSort[$key][$uniqid] = $value;
        }
    }
    array_multisort($arrSort[$field], constant($sort), $array);
    return $array;
}




















